﻿using System.Collections;
using UnityEngine;
using UnityEngine.Networking;

namespace Framework.Manager
{
    public class NetworkManager : ManagerBase<NetworkManager>
    {
        #region Manager通用
        private NetworkManager() { }
        #endregion

        private string mUrl = string.Empty;
        /// <summary>HttpUrl</summary>
        public string HttpUrl
        {
            get => mUrl;
            set
            {
                if (value.EndsWith("/"))
                    mUrl = value.Remove(value.Length - 1);
                else
                    mUrl = value;
            }
        }

        protected override void OnInit()
        {
        }

        #region Http
        public void HttpGet(string pApi)
        {
            StartCoroutine(WebRequestGet(pApi));
        }

        private IEnumerator WebRequestGet(string pApi)
        {
            string url = string.Format("{0}/{1}", HttpUrl, pApi);
            using (UnityWebRequest webRequest = UnityWebRequest.Get(url))
            {
                yield return webRequest.SendWebRequest();

                if (webRequest.isHttpError || webRequest.isNetworkError)
                {
                    //ManagerCollection.EventManager.SendEvent(pApi, false, webRequest.error);
                }
                else
                {
                    //ManagerCollection.EventManager.SendEvent(pApi, true, webRequest.downloadHandler.text);
                }
            }
        }

        public void HttpPost(string pApi, object[] pParameter = null)
        {

        }

        //private IEnumerator WebRequestPost<T>(T pApiData)
        //{
        //    string url = string.Format("{0}/{1}", HttpUrl, pApiData.Api);
        //    string json = UtilCollection.DataUtil.ClassToJson<T>(pApiData);

        //    using (UnityWebRequest webRequest = UnityWebRequest.Post(url, json, "application/json"))
        //    {
        //        yield return webRequest.SendWebRequest();

        //        if (webRequest.isHttpError || webRequest.isNetworkError)
        //        {
        //            ManagerCollection.EventManager.SendEvent(pApiData.Api, false, webRequest.error);
        //        }
        //        else
        //        {
        //            ManagerCollection.EventManager.SendEvent(pApiData.Api, true, webRequest.downloadHandler.text);
        //        }
        //    }
        //}
        #endregion
    }
}